import datetime

import webapp2
from google.appengine.api import users, blobstore
from google.appengine.ext.webapp import blobstore_handlers
from util.webapp import ShopkeepApplication, ShopkeepHandler
from util.uri import Uri
from .search import SearchPage
from models.Item import Item
from models.User import User

class UserPage(ShopkeepHandler):
	def get(self):
		action = self.request.GET.get('action', 'view')
		user = users.get_current_user()

		data = {
			'user_obj': self.user,
			'token': self.token
		}

		if action == 'view':
			self.render_response('user_view.html', data)
		elif action == 'edit':
			if not user == self.user.id :
				self.abort(403)
			self.render_response('user_edit.html', data)
		elif action == 'upload':
			if not user == self.user.id :
				self.abort(403)
			data['upload_url_photo'] = blobstore.create_upload_url(repr(Uri(self.request.url).relPath('photo')))
			data['upload_url_video'] = blobstore.create_upload_url(repr(Uri(self.request.url).relPath('video')))
			self.render_response('user_upload.html', data)
		else:
			self.abort(400)

	def post(self):
		user = users.get_current_user()
		action = self.request.POST.get('action', 'edit')

		if action == 'edit':
			if self.user.id == user:
				self.user.first_name = self.request.POST.get('first_name', '')
				self.user.email = self.request.POST.get('email', '')
				self.user.last_name = self.request.POST.get('last_name', '')
				self.user.address = self.request.POST.get('address', '')
				self.user.phone_number = self.request.POST.get('phone_number', '')
				self.user.info = self.request.POST.get('info', '')
				self.redirect(self.request.host_url + '/users/' + str(self.user.key().id()))
				return
			else:
				self.abort(403)
		elif action == 'delete':
			if self.user.id == user:
				items = Item.all()
				items.filter("seller =", self.user.id)
				for x in items.run():
					x.delete()
				self.user.delete()
			else:
				self.abort(403)

		self.user.put()
		self.redirect(self.request.host_url)

	@webapp2.cached_property
	def user(self):
		info = self.request.path.split('/')

		user = None
		try:
			user_id= int(info[2])
		except ValueError:
			self.abort(400)

		user = User.get_by_id(user_id)

		if user is None:
			self.abort(404)
			# Should not be reached, since self.abort throws excpt

		return user

class PhotoUpload(blobstore_handlers.BlobstoreUploadHandler, UserPage):
	def post(self):
		photo = self.get_uploads('file')
		blob_info = photo[0]
		self.user.photo = blob_info.key()
		self.user.put()

		self.redirect('/users/{0}'.format(self.user.key().id()))

class VideoUpload(blobstore_handlers.BlobstoreUploadHandler, UserPage):
	def post(self):
		video = self.get_uploads('file')
		blob_info = video[0]
		self.user.video = blob_info.key()
		self.user.put()

		self.redirect('/users/{0}'.format(self.user.key().id()))

app = ShopkeepApplication([
	('/users/.+/photo', PhotoUpload),
	('/users/.+/video', VideoUpload),
	('/users/.+', UserPage),
	webapp2.Route('/users/.+', UserPage, methods=['POST'])
])
